package com.qin.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qin.entity.Shopping;
import com.qin.entity.User;
import com.qin.service.ShoppingService;
import com.qin.service.impl.ShoppingServiceImpl;

import cn.hutool.log.StaticLog;

/**
 * 添加一条记录到购物车
 */
@WebServlet("/addtoshoppingcart")
public class AddtoShoppingCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private ShoppingService shoppingService = new ShoppingServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute("user");
		String bookId = request.getParameter("bookId");
		String bookNum = request.getParameter("bookNum");
		
		StaticLog.debug("拿到用户:{},图书id：{},图书数量：{}", user,bookId,bookNum);
		
		Shopping shopping = new Shopping();
		shopping.setUserId(user.getId());
		shopping.setBookId(Long.parseLong(bookId));
		shopping.setBookNum(Integer.parseInt(bookNum));
		
		// 往数据库添加一条购物车记录
		shoppingService.insertShoppingPlus(shopping,user.getId(),Long.parseLong(bookId));
		
		// 往session中添加一条记录
		int size = shoppingService.getShoppingItemsByUserId(user.getId()).size();
		
		session.setAttribute("shoppingNum", size);
		// 返回成功消息
		response.getWriter().print(size);
	}

}
